package com.nms.dao.impl;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import com.nms.dao.CKEditorDao;
import com.nms.util.SourceUtil;
import com.nms.util.SystemUtil;

public class CKEditorDaoImpl implements CKEditorDao {

	@Override
	public String getContent(String id) {
		File file = new File(SystemUtil.getInstance().getContentPath() + id
				+ ".news");
		String result = "";
		byte[] buffer = null;
		try {
			FileInputStream fis = new FileInputStream(file);
			buffer = new byte[fis.available()];
			fis.read(buffer);
			result = new String(buffer);
			fis.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return result;
	}

	@Override
	public void saveContent(String id, String content) {

		File file = new File(SystemUtil.getInstance().getContentPath() + id
				+ ".news");
		try {
			FileOutputStream fos = new FileOutputStream(file);
			fos.write(content.getBytes());
			fos.flush();
			fos.close();

			
			/* 开发阶段使用的，将新闻文件写回工程目录下*/
			File f = new File(SourceUtil.PropertiesUtil.getProjectContentPath() + id
					+ ".news");
			System.out.println(f.getAbsolutePath());
			FileOutputStream fos1 = new FileOutputStream(f);
			fos1.write(content.getBytes());
			fos1.flush();
			fos1.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void deleteContent(String id) {
		File file = new File(SystemUtil.getInstance().getContentPath() + id
				+ ".news");
		if (file.exists() && file.isFile())
			file.delete();

		/* 开发阶段使用的，将新闻文件写回工程目录下*/
		File f = new File(SourceUtil.PropertiesUtil.getProjectContentPath() + id
				+ ".news");
		if (f.exists() && f.isFile())
			f.delete();
	}

	@Override
	public void save(String url, String content) {

		File file = new File(url);
		try {
			FileOutputStream fos = new FileOutputStream(file);
			fos.write(content.getBytes());
			fos.flush();
			fos.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void delete(String url) {
		File file = new File(url);
		if (file.exists() && file.isFile())
			file.delete();
	}

	@Override
	public String get(String url) {
		File file = new File(url);
		String result = "";
		byte[] buffer = null;
		try {
			FileInputStream fis = new FileInputStream(file);
			buffer = new byte[fis.available()];
			fis.read(buffer);
			result = new String(buffer);
			fis.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return result;
	}

}
